<?php

namespace Staff\Controller;

use Think\Image;
use Think\Page;
use Org\Net\Http;
use Think\Controller;

class OrderController extends AuthController {
	/**
	 * 获取添加订单
	 */
	public function index() {
		if (IS_POST) {
			$staff = session ( "auth" );
			$data ['staff'] = $staff ['name'];
			$nums = $_POST ['num'];
			$order = D ( "Order" );
			$data ['uid'] = $_POST ['uid'];
			$data ['remark'] = $_POST ['remark'];
			$data ['address'] = $_POST ['address'];
			$data ['area'] = $_POST ['area'];
			$data ['phone'] = $_POST ['phone'];
			$data ['username'] = $_POST ['name'];
			$data ['payment'] = $_POST ['payment'];
			$data ['ptime'] = $_POST ['ptime'];
			$where ['FoodCategory.id'] = array (
					"in",
					$_POST ['category']
			);
			$data = $order->create ( $data );
			// var_dump($where);
			$result = $order->add ( $data );
			if ($result) {
				$foods = D ( "FoodCategory" )->where ( $where )->select ();
				// $foods = D ( 'Food' )->where ( $where )->field ( "id as fid,food_name,food_image,yprice,price,unit" )->select ();
				$count = count ( $foods );
				$i = 0;
				$food_yprice = 0;
				$food_price = 0;
				$carrige_price = 0;
				$oddata = array ();
				foreach ( $foods as $food ) {
					$food ['num'] = $nums [$i];
					$food ['oid'] = $data ['id'];
					$oddata [] = $food;
					$food_yprice += $food ['yprice'] * $food ['num'];
					$food_price += $food ['price'] * $food ['num'];
					$i ++;
				}
				M ( 'OrderDetail' )->addAll ( $oddata );
				$data ['food_yprice'] = $food_yprice;
				$data ['food_price'] = $food_price;
				$result = $order->where ( array (
						'id' => $data ['id']
				) )->save ( $data );
				if ($result) {
					$this->success ( "添加订单成功", "index" );
				} else {
					$this->error ( "修改订单信息出错" );
				}
			} else {
				$this->error ( "添加订单出错" );
			}
		} else {
			$users = M ( 'User' )->order ( array (
					'id' => 'asc'
			) )->select ();
			$areas = M ( 'Area' )->order ( array (
					'id' => 'asc'
			) )->select ();
			$foods = M ( 'Food' )->order ( array (
					'id' => 'asc'
			) )->select ();
			$otimes = M ( 'OrderTime' )->order ( array (
					'id' => 'asc'
			) )->select ();
			$this->assign ( 'users', $users );
			$this->assign ( 'areas', $areas );
			$this->assign ( 'foods', $foods );
			$ptimes = array ();
			foreach ( $otimes as $otime ) {
				if ($otime ['status']) {
					$ptime = "";
					switch ($otime ['type']) {
						case 1 :
							$ptime .= "当天";
							break;
						case 2 :
							$ptime .= "次日";
							break;
					}
					$ptime .= "{$otime['stime']}-{$otime['etime']}";
					$ptimes [] = $ptime;
				}
			}
			$this->assign ( 'ptimes', $ptimes );
			$this->display ();
		}
	}
}
?>